using HCore.Core;
using HCore.Unity.Core;
using UnityEngine;

namespace HCore.Tests.Runtime.PathFinding
{
    public class PathFindingVisual : MonoBehaviour
    {
        private Grid2D<IPathNode> mGrid;
        private bool mIsUpdateMesh;
        private Mesh mMesh;

        private void Awake()
        {
            mMesh = new Mesh();
            GetComponent<MeshFilter>().mesh = mMesh;
        }

        private void LateUpdate()
        {
            if (mIsUpdateMesh)
            {
                mIsUpdateMesh = false;
                UpdateVisual();
            }
        }

        public void SetGrid(Grid2D<IPathNode> grid)
        {
            mGrid = grid;
            UpdateVisual();
            mGrid.AddCellChangedListener(@event => mIsUpdateMesh = true);
        }


        private void UpdateVisual()
        {
            GameUtils.CreateEmptyQuadMeshArrays(
                mGrid.Width * mGrid.Height,
                out var vertices,
                out var uv,
                out var triangles
            );

            ForUtils.For(mGrid.Width, mGrid.Height, (x, y) =>
            {
                var index = x * mGrid.Height + y;
                var quadSize = Vector2.one * mGrid.CellSize; // 获取格子在画布中的长宽数据
                var pathNode = mGrid.GetCell(x, y); // 获取格子对象
                if (pathNode.IsWalkable) quadSize = Vector2.zero;

                GameUtils.AddToMeshArrays(
                    vertices, uv, triangles,
                    index, mGrid.GetCellWorldPosition(x, y) + quadSize * 0.5f, 0f, quadSize,
                    Vector2.zero, Vector2.one);
            });

            // 设置栅格
            mMesh.vertices = vertices;
            mMesh.uv = uv;
            mMesh.triangles = triangles;
        }
    }
}